<template>
  <!-- 创建发货单 -->
  <el-dialog
    v-model="dialogVisible"
    title="创建发货单"
    width="50%"
    :before-close="handleClose"
  >
    <el-form
      v-loading="loading"
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      status-icon
    >
      <el-row :gutter="24">
        <el-alert
          v-if="ruleForm.status === 2"
          class="mb-30"
          :title="`审核未通过，驳回原因：${ruleForm.remarks}`"
          type="error"
          show-icon
        />
        <el-col :span="24" class="pl-0">
          <el-col :span="24" class="wh50">
            <el-form-item label="发货订单：" prop="orderId">
              <el-select
                v-model="ruleForm.orderId"
                size="large"
                class="wh"
                filterable
                placeholder="请选择发货订单"
                @change="onOrderChange"
              >
                <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="`订单：${item.id}&nbsp;&nbsp;(${item.productInfo})&nbsp;&nbsp;${item.productAmount}辆&nbsp;&nbsp;总价：${item.productCurrency}&nbsp;&nbsp;${filters.thousands(item.productSumPrice)}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发货车辆信息：" v-show="orderItems.productInfo">
            <span>{{ orderItems.productInfo }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成交方式：" v-show="orderItems.tradeMode">
            {{ orderItems.tradeMode }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启运港：" v-show="orderItems.startHarborName">
            {{ orderItems.startHarborName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下单数量：" v-show="orderItems.productAmount">
            {{ orderItems.productAmount }}辆
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="mb-lg">选择发货车辆</div>
          <c-table-template
            :data="tableData"
            border
            :row-key="getRowKey"
            ref="multipleTableRef"
            @selection-change="handleSelectionChange"
            style="height: 350px"
          >
            <el-table-column
              type="selection"
              align="center"
              width="55"
              :reserve-selection="true"
            />
            <el-table-column label="车架号" align="center" prop="vin" />
            <el-table-column label="车辆状态" align="center" prop="status" />
            <el-table-column
              label="出口申请单号"
              align="center"
              prop="carOutApplyId"
            />
          </c-table-template>
          <div class="table-footer">
            <span>共选择 {{ multiples.length }} 辆车</span>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :loading="buttonLoading" size="large" @click="handleClose"
        >取 消</el-button
      >
      <el-button
        :loading="buttonLoading"
        size="large"
        type="primary"
        @click="handleSubmit"
        >确 定</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { deepClone } from "@/utils/index.js";
const emits = defineEmits(["change"]);
const { proxy } = getCurrentInstance();
const dialogVisible = ref(false);
const loading = ref(false);
const buttonLoading = ref(false);
const ruleForm = ref({});
const multiples = ref([]);
const options = ref([]);
const orderItems = ref({});
const tableData = ref([]);
const ruleFormRef = ref();
const multipleTableRef = ref();

const handleSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (multiples.value.length <= 0) {
        ElMessage.warning("请选择发货车辆！");
        return;
      }
      const data = deepClone(ruleForm.value);
      data.vinList = multiples.value.map((x) => {
        return x.vin;
      });
      try {
        buttonLoading.value = true;
        let url = "/sellerDeliveryList/apply";
        if (data.id) {
          url = "/sellerDeliveryList/reapply";
        }
        await proxy.$post({ url, data });
        ElMessage.success("操作成功");
        emits("change");
        handleClose();
        buttonLoading.value = false;
      } catch (error) {
        buttonLoading.value = false;
      }
    }
  });
};
const handleOpen = async (item) => {
  loading.value = true;
  orderItems.value = {};
  dialogVisible.value = true;
  try {
    let url = "/buyerOrderList/getListBySeller";
    const list = await proxy.$get({ url });
    options.value = list;
    if (item && item.id) {
      url = "/sellerDeliveryList/getById";
      const res = await proxy.$get({ url, params: { id: item.id } });
      const orderId = res.deliveryList.orderId;
      ruleForm.value = {
        orderId,
        id: res.deliveryList.id,
        status: res.deliveryList.status,
        remarks: res.deliveryList.remarks,
      };
      orderItems.value = list.find((x) => x.id === orderId);

      url = "/sellerDeliveryList/deliveryCarList";
      const tableList = await proxy.$get({ url, params: { orderId } });
      tableData.value = tableList;
      tableList.forEach((x) => {
        res.carList.forEach((r) => {
          if (x.vin === r.vin) {
            multiples.value.push(x);
            multipleTableRef.value.tableRef.toggleRowSelection(x, true);
          }
        });
      });
    }

    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
const getRowKey = (item) => {
  return item.vin;
};
const onOrderChange = async (orderId) => {
  if (multiples.value.length > 0) {
    multiples.value = [];
    multipleTableRef.value.tableRef.clearSelection();
  }
  const url = "/sellerDeliveryList/deliveryCarList";
  const params = {
    orderId,
  };
  orderItems.value = options.value.find((x) => x.id === orderId);
  loading.value = true;
  try {
    const res = await proxy.$get({ url, params });
    tableData.value = res || [];
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
const handleSelectionChange = (list) => {
  multiples.value = list;
};
const handleClose = () => {
  if (multiples.value.length > 0) {
    multiples.value = [];
    multipleTableRef.value.tableRef.clearSelection();
  }
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
};
const rules = ref({
  orderId: [
    {
      required: true,
      message: "请选择发货订单",
      trigger: "change",
    },
  ],
});
defineExpose({
  handleOpen,
});
</script>
<style lang="less" scoped>
.table-footer {
  background: rgb(241, 241, 241);
  color: rgb(32, 32, 32);
  font-size: 14px;
  font-weight: 500;
  border-bottom: var(--el-table-border);
  padding: 12px 16px;
}
</style>
